import { AnyAction } from "redux";
import * as TYPES from "../actiontypes";

export interface ProfileState {
	loginState: string; //当前用户的登录状态
	user: any; //当前已经登录的用户信息
	error: string | null; //错误信息
}

const ProfileState: ProfileState = {
	loginState: "UNLOGIN",
	user: null,
	error: null,
};

export default function (state: ProfileState = ProfileState, action: AnyAction) {
	switch (action.type) {
		case TYPES.VALIDATE:
			if (action.payload.success) {
				return {
					...state,
					loginState: "LOGIN",
					user: action.payload.data, //设置用户名
					error: null, //没有错误
				};
			} else {
				return {
					...state,
					loginState: "UNLOGIN",
					user: null, //用户名为空
					error: action.payload, //错误对象赋值
				};
			}
		case TYPES.LOGOUT:
			return {
				...state,
				loginState: "UNLOGIN",
				user: null,
				error: null,
			};
		case TYPES.CHANGE_AVATAR:
			return { ...state, user: { ...state.user, avatar: action.payload } };
		default:
			return state;
	}
}
